<script setup lang="ts">
import { ref, watch } from 'vue'
import { Tree } from 'ant-design-vue'
import { organizationApi } from '@/api/modules/organization'
import type { Organization } from '@/types/organization'

const props = defineProps<{
  value?: number[]
}>()

const emit = defineEmits<{
  (e: 'update:value', value: number[]): void
}>()

// 组织类型定义
const organizationType = {
  COLLEGE: 1,
  MAJOR: 2,
  CLASS: 3
} as const

const loading = ref(false)
const treeData = ref<any[]>([])
const checkedKeys = ref<number[]>([])

// 转换树形数据，只在班级节点显示复选框
const convertToTreeData = (items: Organization[]): any[] => {
  return items.map(item => ({
    key: item.id,
    title: item.name,
    children: item.children ? convertToTreeData(item.children) : undefined,
    // 只有班级节点显示复选框
    checkable: item.type === organizationType.CLASS,
    // 非班级节点禁用选择
    selectable: false,
    // 添加类型标识
    type: item.type
  }))
}

// 获取组织树数据
const getTreeData = async () => {
  loading.value = true
  try {
    const data = await organizationApi.getTree()
    treeData.value = convertToTreeData(data || [])
  } catch (error) {
    console.error('获取组织树数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理选中值变化
const handleCheck = (checked: any, e: any) => {
  // 只发送班级节点的ID
  const classKeys = checked.filter((key: number) => {
    const findNode = (nodes: any[]): boolean => {
      for (const node of nodes) {
        if (node.key === key) {
          return node.type === organizationType.CLASS
        }
        if (node.children) {
          const found = findNode(node.children)
          if (found) return true
        }
      }
      return false
    }
    return findNode(treeData.value)
  })
  
  checkedKeys.value = classKeys
  emit('update:value', classKeys)
}

// 监听外部值变化
watch(() => props.value, (newVal) => {
  checkedKeys.value = newVal || []
}, { immediate: true })

// 初始化
getTreeData()
</script>

<template>
  <Tree
    :checked-keys="checkedKeys"
    :tree-data="treeData"
    :loading="loading"
    checkable
    :default-expand-all="true"
    @check="handleCheck"
  />
</template>

<style scoped>
/* 可以添加一些自定义样式 */
</style> 